<template>
    <div>
        <NavBar :title="title"></NavBar>
        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field v-model="username" name="username" label="手机号" placeholder="手机号"
                    :rules="[{ pattern, message: '请填写手机号' }]" />
                <van-field v-model="password" :type="start ? 'password' : 'text'" name="password" label="密码"
                    placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]">
                    <template #button>
                        <van-icon name="closed-eye" @click="start = !start" />
                    </template>
                </van-field>
                <van-field v-model="sms" center clearable label="短信验证码" placeholder="请输入短信验证码"
                    :rules="[{ required: true, message: '请填写密码' }]">
                    <template #button>
                        <van-button size="small" type="primary" @click="yzm" :disabled="time ? true : false">{{ time ?
                            time : '发送验证码' }}</van-button>
                    </template>
                </van-field>
            </van-cell-group>
            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    登录
                </van-button>
            </div>
        </van-form>
        <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit" @click="zc">
                注册
            </van-button>
        </div>
    </div>
</template>

<script setup>
import NavBar from '@/components/NavBar.vue';
const title = '登录'
const pattern = /^1[1-9]\d{9}$/
import { ref } from 'vue';
const username = ref('');
const password = ref('');
const sms = ref('');
const time = ref('');
let timer;
const yzm = () => {
    time.value = 10
    sms.value = Math.floor(Math.random() * 100000)
    timer = setInterval(() => {
        time.value--
        if (time.value == 0) {
            clearInterval(timer)
        }
    }, 1000);
}
const start = ref(true)
import { loginApi } from '@/api/api';
import { useRoute, useRouter } from 'vue-router';
const router = useRouter()
const route = useRoute()
const onSubmit = (values) => {
    console.log('submit', values);
    loginApi(username.value, password.value).then(res => {
        console.log(res);
        localStorage.setItem('token', res.data.data.token)
        localStorage.setItem('username', res.data.data.username)
        router.push('/')
    })
};
const zc = () => {
    router.push('/register')
}
</script>

<style lang="scss" scoped></style>